package com.portal.sso.server.impl;

import cn.hutool.core.util.StrUtil;
import com.portal.sso.core.server.TgtServerHander;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@ConditionalOnProperty(name = "portal.sso.manager", havingValue = "redis")
public class TgtServerHanderImpl implements TgtServerHander {
    @Value("${portal.sso.expired}")
    private int timeout;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 判断key是否存在
     * @param tgt
     * @return
     */
    @Override
    public boolean isExist(String tgt) {
        return redisTemplate.hasKey(tgt);
    }

    @Override
    public String getKey(String tgt) {
        String userId = redisTemplate.opsForValue().get(tgt);
        if (StrUtil.isEmpty(userId)) {
            return null;
        }
        redisTemplate.expire(tgt, timeout, TimeUnit.HOURS);
        return userId;
    }

    @Override
    public void remove(String tgt) {
        redisTemplate.delete(tgt);
    }

    @Override
    public boolean refresh(String tgt) {
        if (redisTemplate.opsForValue().get(tgt) == null) {
            return false;
        }
        redisTemplate.expire(tgt, timeout, TimeUnit.HOURS);
        return true;
    }

    @Override
    public void create(String tgt, String userId) {
        redisTemplate.opsForValue().set(tgt, userId, timeout,
                TimeUnit.HOURS);
    }
}
